/* Copyright (C) 2008 Sahid Ferdjaoui <sahid@funraill.org>
 *
 *   This file is part of Postmemd.
 *
 * Postmemd is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#ifndef PM_POLL_H
#define PM_POLL_H


/**
 * @file pm_poll.h
 * @brief Postmem pollin
 */

#include "ev.h"

#include <netinet/in.h>
#include <sys/socket.h>


/**
 * Define all types
 */
typedef int sfd_t; /** socket file descriptor */
typedef int pfd_t; /** pipe file descriptor */

typedef struct io_poller {
	sfd_t listener; /** first file descriptor */
	ev_io event;    /** libev, structure event */
} io_poller;


/**
 * Create a new socket.
 * @param sock The new socket
 * @param interface The interface adress
 * @param port The port to connect
 * @param backlog The queue length waiting connection
 */
int pm_socket_create (sfd_t * sock, struct in_addr interface, int port, int backlog);

/**
 * Record file descriptor in event loop.
 * @param EV_P_ The event loop.
 * @param event The ev_io event.
 * @param fd The file descriptor.
 * @param revents The flag of the event type (EV_READ, EV_WRITE)
 */
void pm_record_fd (EV_P_ struct ev_io * event, int fd, void * handler, int revent);

/**
 * Remove file descriptor in event loop.
 * @param EV_P_ The event loop.
 * @param event The ev_io event.
 */
void pm_remove_fd (EV_P_ struct ev_io * event);

/**
 * Event handler
 * @param EV_P_ The event loop.
 * @param w The ev_io catched structure
 * @param revents The flag of the event type (EV_READ, EV_WRITE)
 */
void pm_event_handler (EV_P_ struct ev_io * w, int revents);

/**
 *
 *
 *
 */
void pm_event_handler_slaves (EV_P_ struct ev_io * w, int revents);

/**
 * Write file descriptor.
 * @param fd The file descriptor.
 * @param * buffer The write buffer.
 * @param * buffer_bytes The number of bytes writed.
 */
int pm_poll_write_fd (int fd, char * buffer, int * buffer_bytes, int * writed);

/**
 * Read file descriptor.
 * @param fd The file descriptor.
 * @param * buffer The read buffer.
 * @param * buffer_bytes The number of bytes readed.
 */
int pm_poll_read_fd (int fd, char ** buffer, int * buffer_bytes);

#endif
